package com.cyc.controller;

import com.cyc.model.Information;
import com.cyc.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = {"/","/login"})
    public String index(){
        return "login";
    }
    //注册操作
    @RequestMapping(value = "/reg",method = RequestMethod.POST)
    @ResponseBody
    public String reg(@RequestBody Information information){
        userService.reg(information);
        return "1";
    }
    //登出
    @RequestMapping("/logout")
    public String logout(){
        return "logout";
    }
    @RequestMapping("/show")
    public String show(){
        return "show";
    }
    @RequestMapping("/showst")
    public String showst(){
        return "show_student";
    }
    //登录操作
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(@RequestParam(value = "title", required = false) String username,
                        @RequestParam(value = "password", required = false) String password,
                        @RequestParam(value="isRememberMe", defaultValue="0") Integer isRememberMe,
                        HttpServletRequest request,
                        Model model) {
        //生成用户登录的载体
        Subject subject = SecurityUtils.getSubject();
        //封装用户登录的数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            //执行登录的方法
            subject.login(token);
        } catch (UnknownAccountException e) {
            //出现用户不存在异常
            model.addAttribute("msg", "用户名不存在");
            return "login";
        } catch (IncorrectCredentialsException e) {
            //出现用户密码错误的异常
            System.out.println(e);
            model.addAttribute("msg", "密码错误");
            return "login";
        }
        //设置记住我
        if(isRememberMe==1) {
            token.setRememberMe(true);
        }
        //subject.getPrincipal()获取登录的实例
        request.getSession().setAttribute("user", subject.getPrincipal());
        //给欢迎页面用
        model.addAttribute("user",token);
        //查看是否有admin的权限
        if (subject.isPermitted("user:all")) {
            return "welecome";
        }else if (subject.isPermitted("user:st")) {
            return "stuWelecome";
        }
        return null;
    }

}
